# -*- coding: utf-8 -*-

import cgi, os
import logging

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db

from gaesessions import get_current_session
from db import Thread, Mp
import misc

webapp.template.register_template_library('tag.filter')

class Box(webapp.RequestHandler):
	pseudo = ""
	tpl_val = {}
	who = ""
	state = None
	eq 	= ""
	lvl	= 1

	def __init__(self):
		"""Reset every attribute before using the object."""
		self.pseudo = ""
		self.tpl_val = {}
		self.who = ""
		self.state = None
		self.eq = ""
		self.lvl = 1
	
	def setThread(self):
		"""Get the list of thread."""
		thread = Thread.all()
		thread = thread.order('stateIn')
		thread = thread.filter('%s IN'%self.who, (self.pseudo, 
														self.pseudo.lower()))
		if not self.state == None:
			self.tpl_val['threads'] = thread.filter('%s %s'%
											(self.state, self.eq), self.lvl)
		else:
			self.tpl_val['threads'] = thread

	def process(self, page):
		"""
		Process the demand, and provide the page.

		This method is the core of every boxes. It get some variables,
		put every thing in the right place, and call the template render.
		
		"""
		s = get_current_session()
		c = misc.get_cookie(self.request)
		# nickname
		try:
			self.pseudo = s['pseudo']
		except (NameError,TypeError, KeyError):
			try:
				self.pseudo = c['pseudo']
			except KeyError:
				self.redirect('/guest')
				return
		self.tpl_val['pseudo'] = self.pseudo

		for x in self.request.arguments():
			self.tpl_val[x] = self.request.get(x, '')
		if os.environ['SERVER_SOFTWARE'].startswith('Dev'):
			self.tpl_val['local'] = True

		# getting the thread
		self.setThread()
		if self.request.get('cite', '') != '':
			self.tpl_val['cite'] = Mp.get( db.Key(self.request.get('cite','')) ).message

		path = os.path.join(os.path.dirname(__file__), 'views/%s'%page)
		self.response.out.write(template.render(path, self.tpl_val))

class InboxHandler(Box):
	def get(self):
		"""boite des messages reçu"""
		self.who = 'destin'
		self.state = 'stateIn'
		self.eq = '<='
		self.lvl = 1
		self.tpl_val['type'] = ''

		self.process('index.html')

class OutboxHandler(Box):
	def get(self):
		"""boite des messages envoyé """
		self.who = 'author'
		self.tpl_val['type'] = 'send'

		self.process('send.html')

class PackedHandler(Box):
	def get(self):
		"""archive"""
		self.who = 'destin'
		self.state = 'stateIn'
		self.eq = '>='
		self.lvl = 2
		self.tpl_val['type'] = 'pack'

		self.process('pack.html')
